package com.kelai.jms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.kelai.jms.message.RedisQueueMessage;
import com.kelai.jms.message.RedisTopicMessage;

/**
 * redis消息服务类
 * Created by Luffy on 2017/08/17.
 */
@Component
public class RedisMessageService {

    @Autowired
    private RedisTemplate<String, RedisMessage> redisTemplate;

    /**
     * 发送广播消息
     * @param channelNum
     * @param message
     * @throws Exception
     */
    public void sendTopicMessage(RedisMessageChannelEnum channelNum, RedisTopicMessage message) throws Exception {
        if (!channelNum.type().isAssignableFrom(message.getClass())) {
            throw new Exception("参数类型错误");
        }
        redisTemplate.convertAndSend(channelNum.channel(), message);
    }

    /**
     * 发送队列消息
     * @param channelNum
     * @param message
     * @throws Exception
     */
    public void sendQueueMessage(RedisMessageChannelEnum channelNum, RedisQueueMessage message) throws Exception {
        sendQueueMessage(channelNum, message, Boolean.FALSE);
    }

    /**
     * 发送队列消息
     * @param channelNum
     * @param message
     * @param isPrior
     * @throws Exception
     */
    public void sendQueueMessage(RedisMessageChannelEnum channelNum, RedisQueueMessage message, boolean isPrior)
            throws Exception {
        if (!channelNum.type().isAssignableFrom(message.getClass())) {
            throw new Exception("参数类型错误");
        }
        BoundListOperations<String, RedisMessage> options = redisTemplate.boundListOps(channelNum.channel());
        if (isPrior) {
            options.leftPush(message);
        } else {
            options.rightPush(message);
        }
    }
}
